#### Insurgent Intimidation Results #### 
df = readRDS('data/full_panel_df.rds') %>% 
  filter(cohort == "2011" | cohort == "2012" | cohort == '2013' | cohort == '10000') %>% 
  filter(year >= 2008) %>% 
  filter(year < 2014) %>% 
  mutate(
    treat = ifelse(treated_ever==1, as.numeric(year>=cohort, 1,0), 0), 
    intim_sum = intim_threat+intim_violent, 
    intim_sum_ln = log(intim_sum+1), 
    intim_sum_bin = as.numeric(intim_sum>0, 1,0)
  )

df2 <- df[ ,c('intim_sum', 'intim_sum_ln', 'intim_sum_bin',
              'treat', 'DISTID', 'year', 'cohort')]


J <- 3

att_tjbal <- matrix(, nrow = J, ncol = 3)
out_names <- names(df2)[1:J]


for(j in 1:J){
  
  att_tjbal[j, 1:3] <- print(tjbal(data = df2, Y = out_names[j], D = "treat", 
                                   index = c("DISTID", "year"), demean = F, estimator = "mean", 
                                   vce = "jackknife"))[c(1,2,6)]
  
}

att_tjbal <- as.data.frame(att_tjbal)
att_tjbal$outcome_name <- out_names[1:J]
colnames(att_tjbal)[1:3] <- c('att', 'se', 'pval')
att_tjbal <- att_tjbal %>% 
  mutate(att = ifelse(pval < .05, paste0(att, "*"), att), 
         att = ifelse(pval < .01, paste0(att, "*"), att), 
         att = ifelse(pval < .001, paste0(att, "*"), att), 
  ) %>% 
  mutate_if(is.numeric, as.character)

att_tjbal <- att_tjbal %>% 
  pivot_longer(cols = c('att', 'se', 'pval'))

att_tjbal <- att_tjbal %>% 
  pivot_wider(names_from = outcome_name, 
              values_from = value)

att_tjbal <- rbind.data.frame(att_tjbal,
                              dataset = c("SIGACTS", 'SIGACTS', 'SIGACTS'), 
                              Districts  = c(rep(rep(length(unique(df$DISTID)), J))),
                              Years  = c(rep(rep(length(unique(df$year)), J)))
                              
                              
)


print.xtable(xtable(att_tjbal), booktabs = T,  include.rownames = F, file = 'tables/intim_table.tex')

n_obs = length(unique(df$DISTID))*length(unique(df$year))

round(mean(df$intim_sum[df$treated_ever==0]),2)
round(mean(df$intim_sum_ln[df$treated_ever==0]),2 ) 
round(mean(df$intim_sum_bin[df$treated_ever==0]),2)

round(sd(df$intim_sum),2)
round(sd(df$intim_sum_ln),2 ) 
round(sd(df$intim_sum_bin),2)
